import {
  Swiper,
  SwiperItem,
  View,
  Text,
  Image,
  Button,
  ScrollView,
} from "@tarojs/components";
import Taro, { useLoad, useRouter, useDidShow, useShareAppMessage } from "@tarojs/taro";
import "./index.scss";
import MerchantItem from "../../components/MerchantItem/index";
import { getGlobalData } from "../../globalData";
import UserDialogLogin from "@/components/UserDialogLogin";
import { useState } from "react";
import { request } from "@/utils/request";
import { isLogin, markPhone } from "@/utils/tools";
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui";

export default function Index() {
  const [hasLogin, setHasLogin] = useState(true);
  const [loginDialogVisible, setLoginDialogVisible] = useState(false);
  const [inviteDialogVisible, setInviteDialogVisible] = useState(false);
  const [ruleDesc2, setRuleDesc2] = useState("");
  const [groupId, setGroupId] = useState("");
  const [userPhone, setUserPhone] = useState("");
  const [hotActivityList, setHotActivityList] = useState([]);
  const [familyNum, setFamilyNum] = useState(1);
  const [familyPointsNum, setFamilyPointsNum] = useState(0);
  const [baoZhangNum, setBaoZhangNum] = useState(0);
  const [baoDanNum, setBaoDanNum] = useState(0);
  const [curActivityTypeId, setCurActivityTypeId] = useState(0);
  const [activityTypeList, setActivityTypeList] = useState<any[]>([]);
  const [curTypeActivityList, setCurTypeActivityList] = useState(null);
  // const [isRelease] = useState(getGlobalData('release'));
  const isRelease = getGlobalData('isRelease') || true;
  // 用户邀请变量
  let openid: string = "";

  useShareAppMessage((res) => {
    return {
      title: "万户健康",
      path: `/pages/index/index`,
    }
  })

  function getActivityList(noAuth) {
    request({
      url: "/api/points/activity/getAllTypeActivities",
      noAuth: noAuth,
      success: (data) => {
        if(data.length > 0){
          let storageTypeId = Taro.getStorageSync("/pages/index/index/typeId");
          setActivityTypeList(data)
          let tempTypeObj = data[0]
          if (storageTypeId) {
            let tempTypeObj2 = data.find((type) => {
              return type.typeId === storageTypeId;
            });
            if (tempTypeObj2) {
              tempTypeObj = tempTypeObj2;
            }
          }
          setCurActivityTypeId(tempTypeObj.typeId)
          setHotActivityList(tempTypeObj.pointsActivityDTOS);
          // let tempTypeObj = data.find(type=>{
          //   return type.typeId === curActivityTypeId
          // })
          
          // if(tempTypeObj){
          //   setHotActivityList(tempTypeObj.pointsActivityDTOS);
          // }
        }
        
      },
      fail: (err) => {
        console.log("getActivityList err", err);
      },
      complete: () => {
        console.log('complete')
      }
    });
  }
  function getFamilyGroupPoints() {
    request({
      url: "/api/points/family/getFamilyReceiveRecord",
      success: (data) => {
        setFamilyPointsNum(data.totalPoints || 0);
        Taro.setStorageSync("familyPointsNum", data.totalPoints || 0);
      },
    });
  }
  // 获取家庭成员情况
  function getFamilyGroupList() {
    request({
      url: "/api/points/family/queryList",
      data: {
        token: Taro.getStorageSync("token"),
        openId: Taro.getStorageSync("openid"),
      },
      success: (data) => {
        // console.log("getFamilyGroupList", data);
        setFamilyNum(data.respDataList.length + 1);
      },
    });
  }

  function getFamilyGroupInsurance() {
    request({
      url: "/api/points/family/getFamilyInsurance",
      success: (data) => {
        // console.log('getFamilyGroupInsurance',data)
        if (data.length > 0) {
          // 全家
          let baodanNum = data[0].familyInsuranceDetailDTOList.length;
          if (baodanNum > 0) {
            setBaoDanNum(baodanNum);
          }
          let baozhangNum = data.slice(1).filter((item) => {
            return item.familyInsuranceDetailDTOList.length > 0;
          }).length;
          setBaoZhangNum(baozhangNum);
        }
      },
    });
  }

  // 家庭群邀请 groupId=547&userPhone=15626473067&ruleDesc2=2
  const menuButtonTop = getGlobalData("menuButtonTop");
  const menuButtonHeight = getGlobalData("menuButtonHeight");
  
  function jumpToFamilyPointsPage() {
    console.log('jumpToFamilyPointsPage')
    if (isLogin()) {
      Taro.navigateTo({ url: "/pages/myFamilyPoints/index" });
    } else {
      setLoginDialogVisible(true);
    }
  }
  function jumpToFamilyGroupPage() {
    console.log('jumpToFamilyGroupPage')
    if (isLogin()) {
      Taro.navigateTo({ url: "/pages/myFamilyGroup/index" });
    } else {
      setLoginDialogVisible(true);
    }
  }
  function jumpAddInsurancePage() {
    console.log('jumpAddInsurancePage')
    if (isLogin()) {
      Taro.navigateTo({ url: "/pages/addInsurance/index" });
    } else {
      setLoginDialogVisible(true);
    }
  }
  // 接受邀请对话框
  function acceptInviteDialog() {
    console.log('acceptInviteDialog')
    // 获取openid
    openid = Taro.getStorageSync("openid");
    // 如果未登录
    if (!isLogin()) {
      // 设置邀请同意状态为0
      Taro.setStorageSync("inviteAgree", 0);
      // 创建邀请对象
      var inviteObj = {
        ruleDesc2: ruleDesc2,
        shareToType: 10,
        groupId: groupId,
        clientType: 2,
      };
      // 设置邀请群组id
      Taro.setStorageSync("inviteGroupId", groupId);
      // 设置邀请对象
      Taro.setStorageSync("inviteObj", inviteObj);
      // 显示登录对话框
      setLoginDialogVisible(true);
      // 隐藏邀请对话框
      hideInviteDialog();
      return;
    }
    // 发送请求
    request({
      url: "/api/points/family/agree/" + groupId + "/2/" + openid,
      data: {
        token: Taro.getStorageSync("token"),
        openId: openid,
      },
      method: "post",
      success: function (res) {
        // 显示提示信息
        Taro.showToast({
          icon: "none",
          title: "您已加入家庭群",
        });
      },
      complete: function () {
        // 隐藏邀请对话框
        hideInviteDialog();
        console.log('acceptInviteDialog complete')
        getFamilyGroupList()
        
      },
    });
  }
  function getInviteStatus(options) {
    console.log("getInviteStatus:", options);
    request({
      url: `/api/points/family/queryGroupState/${options.groupId}`,
      noAuth: true,
      success(status) {
        console.log("queryGroupState status:", status);
        if (status == 2) {
          Taro.showToast({
            icon: "none",
            title: "已拒绝邀请，重新发送邀请可再次加入",
            duration: 3000,
          });
        } else if (status == 1) {
          Taro.showToast({
            icon: "none",
            title: "您已加入家庭组",
          });
        } else {
          setGroupId(options.groupId);
          setUserPhone(options.userPhone);
          setRuleDesc2(options.ruleDesc2);
          const inviteGroupId = Taro.getStorageSync("inviteGroupId");
          console.log("userPhone:", userPhone, options.userPhone);
          console.log("inviteGroupId:", inviteGroupId);
          if (
            options.userPhone !== Taro.getStorageSync("custPhone") &&
            (!inviteGroupId || groupId != inviteGroupId)
          ) {
            setInviteDialogVisible(true);
          }
        }
      },
    });
  }

  function hideInviteDialog() {
    setInviteDialogVisible(false);
    
  }
  function closeInviteDialog() {
    openid = Taro.getStorageSync("openid");
    console.log("closeInviteDialog");
    var inviteObj = {
      ruleDesc2: ruleDesc2,
      shareToType: 11,
      groupId: groupId,
      clientType: 2,
    };
    hideInviteDialog();
    Taro.setStorageSync("disagreeInviteObjGroupId", groupId);
    Taro.setStorageSync("inviteObj", inviteObj);
    console.log('isLogin:',!!isLogin())
    if (!isLogin()) {
      setLoginDialogVisible(true);
      return;
    }
    if(!!isLogin())
    request({
      url: "/api/points/family/disAgree/" + groupId + "/2/" + openid,
      data: {
        token: Taro.getStorageSync("token"),
        openId: openid,
      },
      method: "post",
      complete: function () {
        console.log('disAgree complete')
        hideInviteDialog();
      },
    });
  }

  function jumpToFamilyIns() {
    console.log('jumpToFamilyIns')
    if (isLogin()) {
      Taro.navigateTo({
        url: "/pages/familyIns/index",
      });
    } else {
      setLoginDialogVisible(true);
    }
  }
  

  function jumpToActivityDetailPage(activity) {
    console.log('jumpToActivityDetailPage')
    // if (isLogin()) {
    //   Taro.navigateTo({
    //     url: "/pages/activityDetail/index?activityId=" + activity.id,
    //   });
    // } else {
    //   setLoginDialogVisible(true);
    // }
    Taro.navigateTo({
      url: "/pages/activityDetail/index?activityId=" + activity.id,
    });
  }
  // 获取分类列表


  function changeActivityTypeId(typeId){
    Taro.setStorageSync('/pages/index/index/typeId',typeId)
    setCurActivityTypeId(typeId)
    let curActivityList = activityTypeList.find(item => item.typeId == typeId)
    setHotActivityList(curActivityList.pointsActivityDTOS)
  }

  function goFuliBuyPage(){
    if (isLogin()) {
      Taro.navigateTo({
        url: "/pages/buyMedicine/index",
      })
    }else{
      setLoginDialogVisible(true)
    }
    
  }

  useDidShow(() => {
    console.log("useDidShow");
    let token = Taro.getStorageSync("token");
    if (token) {
      setHasLogin(true);
      // 获取家庭组积分
      getFamilyGroupPoints();
      // 查看家庭成员保险情况
      getFamilyGroupInsurance();
      getActivityList(false);
      getFamilyGroupList();
    } else {
      setHasLogin(false);
      getActivityList(true);
    }
    openid = Taro.getStorageSync("openid");
    // 获取活动列表
  });
  // 用户邀请链接 groupId=547&userPhone=15626473067&ruleDesc2=2
  useLoad((options) => {
    // 获取分裂列表
    // getActivityTypeList()
    console.log("Page loaded.", options);
    if (options.groupId && options.userPhone && options.ruleDesc2) {
      let disagreeInviteObjGroupId = Taro.getStorageSync(
        "disagreeInviteObjGroupId"
      );
      if (
        disagreeInviteObjGroupId &&
        Number(disagreeInviteObjGroupId) === Number(options.groupId)
      ) {
        // 已经被拒绝过了
        Taro.showToast({
          icon: "none",
          title: "已拒绝邀请，可重新发送邀请",
          duration: 3000,
        });
      } else {
        // 查询用户是否拒绝过
        getInviteStatus(options);
      }
    }else {
      // 如果没有邀请，登录已过期，就显示登录
      if(options.showLogin ==='1'){
        setLoginDialogVisible(true)
      }
    }
  });

  return (
    <View className="index">
      <View className="header">
        {/* 顶部 */}
        <Swiper
          className="swiper"
          indicatorColor="#999"
          indicatorActiveColor="#333"
          circular
          indicatorDots
          autoplay
        >
          <SwiperItem className="swiper-item">
            <Image
              className="image"
              src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/ad1.jpg"
              mode="aspectFill"
            />
          </SwiperItem>
          <SwiperItem className="swiper-item">
            <Image
              className="image"
              src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/ad2.jpg"
              mode="aspectFill"
            />
          </SwiperItem>
          <SwiperItem className="swiper-item">
            <Image
              className="image"
              src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/ad3.jpg"
              mode="aspectFill"
            />
          </SwiperItem>
        </Swiper>
        <View className="logo" style={`height:${menuButtonHeight}`}>
          <Image
            className="logo-img"
            src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/logo.png"
            mode="widthFix"
          />
        </View>
        {/* 积分帐户标题 */}
        <View className="point">
          <View className="point-header">
            <View className="avatar">
              <Image
                className="avatar-img"
                src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/avater.png"
                mode="widthFix"
              />
              <Text className="avatar-title">你好，今天来集分吧！</Text>
            </View>
            {/* <View className='bind-btn'>
            绑定商户 + 
            </View> */}
          </View>
          <View className="point-content">
            <View
              className="point-item"
              onClick={() => {
                jumpToFamilyGroupPage();
              }}
            >
              <Image
                className="point-item-img"
                src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/member.png"
                mode="widthFix"
              />
              <Text className="point-item-title">家庭成员</Text>
              <Text className="point-item-num">{familyNum}</Text>
            </View>
            {/* <View className='point-item'>
              <Image className='point-item-img' src='https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/passbook.png' mode='widthFix' />
              <Text className='point-item-title'>绑定商户</Text>
              <Text className='point-item-num'>48</Text>
            </View> */}
            <View
              className="point-item"
              onClick={() => {
                jumpToFamilyPointsPage();
              }}
            >
              <Image
                className="point-item-img"
                src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/coin.png"
                mode="widthFix"
              />
              <Text className="point-item-title">全家积分</Text>
              <Text className="point-item-num">{familyPointsNum}</Text>
            </View>
          </View>
        </View>
      </View>

      <View className="page-content">
        {/* 全家保障 */}
        { isRelease && 
          <View className="family">
            <View className="family-header">
              <Text className="title">全家保障</Text>
              <View className="ins-btn">
                <Text className="ins-btn-text" onClick={jumpAddInsurancePage}>
                  领取保障
                </Text>
                {/* <AtIcon value='chevron-right' size='14' color='#FFF'></AtIcon> */}
              </View>
            </View>
            <View className="family-content" onClick={jumpToFamilyIns}>
              <View className="content-left">
                <View className="info">
                  <Text className="danger">{baoZhangNum}</Text>人保障中
                </View>
                <View className="info">
                  <Text className="danger">{baoDanNum}</Text>份保单
                </View>
              </View>
              <View className="content-right"> 立即查看 </View>
            </View>
          </View>
        }
        <View className='fuli-buy' onClick={goFuliBuyPage}>
          <View className='fuli-buy-title'>福利购药</View>
        </View>
        {/* 热门积分商户 */}
        <View className="account">
          <View className="account-header">
            <Text className="title">热门积分活动</Text>
          </View>
          <View className="account-type">
            <ScrollView scrollX scrollWithAnimation>
              <View className="type-list">
                {activityTypeList.map((type,index) => {
                    return <View key={index} className={["type-item",curActivityTypeId ===type.typeId ? 'active' : ''].join(' ')} onClick={() => {changeActivityTypeId(type.typeId)}}>{type.title}</View>;
                  })}
              </View>
            </ScrollView>
          </View>
          <View className="account-content">
            {hotActivityList.map((activity: any, index: number) => (
              <View
                className="jifen-item"
                onClick={() => {
                  jumpToActivityDetailPage(activity);
                }}
              >
                <View className="jifen-item-header">
                  <View className="left">
                    <View className="name">{activity.title}</View>
                    <View className="num">+{activity.points}</View>
                  </View>
                  <View
                    className={[
                      "right",
                      activity.finished ? "finished" : "",
                    ].join(" ")}
                  >
                    <Text
                      className={[
                        "txt",
                        activity.finished ? "complete" : "pending",
                      ].join(" ")}
                    >
                      {activity.finished ? "任务完成" : "去完成"}
                    </Text>
                  </View>
                </View>
                <View className="jifen-item-content">
                  <Image
                    className="image"
                    src={activity.coverImage}
                    mode="aspectFill"
                  ></Image>
                </View>
              </View>
            ))}
            <View className="account-item"></View>
          </View>
        </View>
        {/* 热门积分活动 */}
      </View>
      <UserDialogLogin
        visible={loginDialogVisible}
        title="提示"
        content="请先登录"
        btnText="去登录"
        close={() => {
          setLoginDialogVisible(false);
        }}
      ></UserDialogLogin>
      {/* 邀请弹窗 */}
      <AtModal isOpened={inviteDialogVisible}>
        <AtModalHeader>家庭群邀请</AtModalHeader>
        <AtModalContent>
          <View className="txt">
            你的{ruleDesc2}（{markPhone(userPhone)}），邀请你加入家庭群!
          </View>
          <View className="txt">
            加入家庭群，可以更好的了解和管理家人的健康，更方便的与家人沟通！
          </View>
        </AtModalContent>
        <AtModalAction>
          <Button onClick={closeInviteDialog}>忽略</Button>
          <Button type="primary" onClick={acceptInviteDialog}>
            接受
          </Button>
        </AtModalAction>
      </AtModal>
    </View>
  );
}
